package com.huawei.M01.iterator.july;

/**
 * 功能：使用前后max的方式，求最大值
 *
 * @author zhiwu
 * @Data 2023/7/12 0:08
 */
public class TrapWater2 {
    public int trap(int[] height) {
        int ans = 0;
        // 获取前后缀最大值的集合
        int[] preMax = new int[height.length];
        int[] sufMax = new int[height.length];
        preMax[0] = height[0];
        sufMax[height.length - 1] = height[height.length - 1];
        for (int i = 1; i < height.length; i++) {
            preMax[i] = Math.max(preMax[i - 1], height[i]);
        }
        for (int i = height.length - 2; i >= 0; i--) {
            sufMax[i] = Math.max(sufMax[i + 1], height[i]);
        }

        for (int i = 1; i < height.length - 1; i++) {
            int up = Math.min(preMax[i - 1], sufMax[i + 1]);
            if (up > height[i]) {
                ans += up - height[i];
            }
        }
        return ans;
    }
}
